
from PySide6.QtCore import QThread, Signal
import serial
from time import sleep
class SerialThread(QThread):
    data_signal = Signal(bytes)
    def __init__(self,port,baud, datebit, parity, stopbit):
        super().__init__()
        self.serial_conn = None
        self.port = port
        self.baud = baud
        self.datebit = datebit
        self.parity = parity
        self.stopbit = stopbit
        self._rx_cnt = 0
        self.__data = []
        # self.__len = len
        self.__running = True

    def stop(self):
        self.__running = False
        self.wait()


    def run(self):
        # 在这里执行你的任务
        print("进入接收线程")
        try:
            self.serial_conn = serial.Serial(self.port, self.baud,self.datebit,self.parity,self.stopbit,timeout=1)
            while self.__running:
                if self.serial_conn.in_waiting > 0:
                    self._rx_cnt = self.serial_conn.in_waiting
                    # 读取串口数据
                    self.__data = self.serial_conn.read(self.serial_conn.in_waiting)
                    # 将字节数据转换为字符串
                    message = self.__data.hex().upper()
                    # print("Received:",message)
                    self.data_signal.emit(message)
                else:
                    QThread.msleep(500) #防止线程占用cpu过高
        except serial.SerialException as e:
           print(f"Serial error: {e}")
        finally:
            if self.serial_conn and self.serial_conn.is_open:
                self.serial_conn.close()
                print("线程关闭")
